<?php

namespace app\controller\adminapi\open;

use app\common\model\addon\Addons;
use app\common\model\open\OpenTemplate as OpenTemplateModel;
use app\common\services\table\Column;
use app\common\services\table\DataTable;
use EasyWeChat\Factory;
use FormBuilder\Driver\CustomComponent;
use hiduoke\controller\AdminController;
use hiduoke\services\CloudServer;
use hiduoke\services\FormBuilder as Form;

// TODO 这里还没完善抖音的配置
class OpenTemplate extends AdminController
{
    /**
     * @var OpenTemplateModel
     */
    public $model;

    /**
     * @var CloudServer
     */
    public $cloud;

    public function initialize()
    {
        $this->model = new OpenTemplateModel();
        $this->cloud = new CloudServer();
    }


    /**
     * 微信小程序服务商管理端配置
     * @param $id
     * @param $type
     * @return \think\response\Json
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function form($id = 0)
    {
        $rule = array();
        //创建表单
        $row = $this->model->findOrEmpty($id); //创建表单
        $form = Form::createForm("/adminapi/open.open_template/save?id=" . $id)->setMethod("POST");
        $open_id = input('open_id', 0);
        if (!$open_id) {
            return $this->error("请选择小程序");
        }
        $open = (new \app\common\model\open\Open())->where(['id' => $open_id])->find();
        // 获取当前的类型
        $addons = (new Addons())->where(['type' => 2, 'app_type' => $open['type']])->select();

        $options = [];
        foreach ($addons as $key => $value) {
            $options[] = array(
                'label' => $value['title'],
                'value' => $value['name']
            );
        }
        //新增表单
        $rule[] = Form::input('name', '模板名称', $row['name'] ?? "")->required();
        $rule[] = Form::input('desc', '模板描述', $row['desc'] ?? "");
        $rule[] = Form::select('addon_name', '绑定应用', $row['addon_name'] ?? "")->options($options)
            ->effect(['help' => '设置绑定的应用，选择后，该应用将会可选为服务商扫码授权模式'])
            ->required();
        // 选择默认授权方式
        $rule[] = Form::radio("auth_type", "授权方式", $row['auth_type'] ?? 'manual')
            ->button()
            ->options(
                [
                    ['label' => '自建小程序（手动配置）', 'value' => 'manual'],
                    ['label' => '开放平台授权（扫码授权）', 'value' => 'open'],
                    ['label' => '用户自由选择配置方式', 'value' => 'auto'],
                ]
            )->effect(['help' => '设置当前绑定应用的授权方式']);

        $template_options = [];
        // 模板ID选择
        if ($open['type'] == 'wx') {
            try {
                $WechatOpenAPI = Factory::openPlatform($open['config']);
                $res = $WechatOpenAPI->code_template->list();
            } catch (\Throwable $th) {
                $res['errcode'] =  -1;
            }
            if ($res['errcode'] == 0) {
                foreach ($res['template_list'] as $key => $value) {
                    $template_options[] = [
                        'label' => "【" . $value['source_miniprogram'] . "】(ID:" . $value['template_id'] . ")-" . $value['user_desc'],
                        'value' => $value['template_id'] . ''
                    ];
                }
            }
            $rule[] = Form::select('template_id', '模板ID', $row['template_id'] ?? "")
                ->allowCreate(true)->filterable(true)
                ->options($template_options)->effect(['help' => '设置模板ID，如果没有模板ID,请检查开放平台配置和模板库中是否有模板，也可以手动填写模板ID']);
        } else {
            $rule[] = Form::input('template_id', '模板ID', $row['template_id'] ?? "")
                ->effect(['help' => '设置模板ID，如果没有模板ID,请检查开放平台配置和模板库中是否有模板，也可以手动填写模板ID']);
        }

        $rule[] = Form::input('version', '默认版本号', $row['version'] ?? "1.0.0")
            ->effect(['help' => '设置当前应用的默认版本号，用户也可以在前端提交时候自己修改，格式为1.0.0']);
        $rule[] = Form::hidden('open_id', $open_id);
        $rule[] = Form::input('remark', '备注', $row['remark'] ?? "");

        // 微信配置
        if ($open['type'] == 'wx') {
            $DkMinappPrivacySetting = new CustomComponent('DkMinappPrivacySetting');
            $rule[] = $DkMinappPrivacySetting
                ->props(['title' => '默认隐私协议配置'])
                ->field('config_privacy_setting_list')
                ->title('')
                ->value($row['config']['privacy_setting_list'] ?? []);
        }


        $title = !$id ? "新增" : "编辑";
        $form->setTitle($title)->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }


    public function table()
    {
        $DataTable = (new DataTable($this->model));
        if ($this->request->param('recycle')) {
            // 回收站
            $DataTable->field([$this->model->getPk(), 'delete_time']);
        }
        $column = $DataTable
            ->setFilterFields(['open_id', 'desc', 'addon_name'])
            ->setAfterField('id', Column::make()->label('应用')->prop('addon')->render('slot')->slotName('addon_slot')->create())
            ->setField('addon_name', ['render' => 'tag'])
            ->setField('logo', ['render' => 'image'])
            ->operation([], ['edit', 'del'])
            ->create();
        return $this->success('ok', ['column' => $column, 'pk' => $this->model->getPk()]);
    }

    public function index()
    {
        if ($this->request->param('select')) {
            return $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->append(['addon'])
            ->paginate($limit);
        return $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }

    public function save()
    {
        $id = input('id', 0);
        $row = $this->model->findOrEmpty($id);
        $formData = getFormData();
        $row->save($formData);
        if ($id) {
            return $this->success("保存成功");
        } else {
            return $this->success('新增成功');
        }
    }
}
